import React, { Component, Fragment } from "react";
import {
  Button,
  Card,
  Descriptions,
  Form,
  Icon,
  InputNumber,
  Modal,
  Popconfirm,
  Select,
  Spin,
  Tag,
  Upload,
} from 'antd';
import styles from './index.less';
import { connect } from 'dva';
import moment from 'moment';
import styled from 'styled-components';
import BaseComponent from '@/components/BaseComponent';
import { njzdImgPrefixUrl } from '@/defaultSettings';
import { PhotoProvider, PhotoView } from 'react-photo-view';
import 'react-photo-view/dist/react-photo-view.css';

const { Option } = Select;

const InVisibleLabel = styled.span`
  visibility: hidden;
  width: 100px;
`;

const UploadHintText = styled.span`
  margin-top: 8px;
  font-size: 12px;
  color: #e43c2e;
`;

const ThumbnailBox = styled.div`
  display: flex;
  align-items: center;
  margin-top: 8px;
  margin-right: 8px;
  position: relative;

  .thumbnailImage {
    width: 60px;
    height: 60px;
    cursor: pointer;
  }

  .rightPart {
    flex: 1;
    text-align: right;
  }

  .delBtn {
    top: 2px;
    right: 4px;
    position: absolute;
    color: red;
    font-size: 10px;
    font-weight: 400;
    cursor: pointer;
  }
`;

const FooterBox = styled.div`
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 16px;
`;

const SpinBox = styled.div`
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
`;

/**
 * 诊疗总量列表
 */
@connect(({ user, loading }) => ({
  currentUser: user.currentUser,
  isLoading: loading.effects['totalnumberofclinics/listAllByUser'],
  isUpdateing: loading.effects['updateRecords/listAllByUser'],
}))
@Form.create()
class TotalNumberofClinics extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 是否正在上传
      isUploading: false,
      // 年份数组
      years: [moment().year(), moment().year() - 1, moment().year() - 2],
      // 被选中的年份
      selectedYear: moment().year(),
      // 当前月份
      nowMonth: moment().month() + 1,
      // 数据源
      data: [],
      //中文月份数组
      months: [
        '一月',
        '二月',
        '三月',
        '四月',
        '五月',
        '六月',
        '七月',
        '八月',
        '九月',
        '十月',
        '十一月',
        '十二月',
      ],
    };
  }

  componentDidMount() {
    Modal.warning({
      centered: true,
      title: '温馨提醒',
      content: (
        <div style={{ color: 'red' }}>
          <p>胃镜总量上报：每月25日24时，平台将自动停止接受上月胃镜总量上报</p>
        </div>
      ),
      okText: '确认',
      cancelText: '取消',
    });
    this.listAllByUser();
  }

  listAllByUser = () => {
    this.execHttp('totalnumberofclinics/listAllByUser', {
      user: this.props.currentUser.id,
      year: this.state.selectedYear,
    })
      .then(resp => {
        if (resp && resp.success) {
          const { list } = resp.data;
          if (list) {
            // 将数据进行拆分,因为图片可能会有多张
            list.forEach(item => {
              const { envienceFileUrl, envienceFilePath } = item;
              if (envienceFileUrl) {
                // 按照|分割envienceFileUrl
                const envienceFileUrlArr = envienceFileUrl.split('|');
                item.envienceFileUrl = envienceFileUrlArr;
              } else {
                item.envienceFileUrl = [];
              }
              if (envienceFilePath) {
                // 按照|分割envienceFilePath
                const envienceFilePathArr = envienceFilePath.split('|');
                item.envienceFilePath = envienceFilePathArr;
              } else {
                item.envienceFilePath = [];
              }
            });
          }
          this.setState(
            {
              data: list,
            },
            () => {
              console.log(JSON.stringify(this.state.data));
            }
          );
        }
      })
      .catch(reason => {});
  };

  updateRecords = ({ data }) => {
    if (this.props.isUpdateing) {
      return;
    }
    const obj = [...data];
    // 对图片数据进行清洗,因为图片可能存在多张
    obj.forEach(item => {
      const { envienceFileUrl, envienceFilePath } = item;
      if (envienceFileUrl) {
        item.envienceFileUrl = envienceFileUrl.join('|');
      }
      if (envienceFilePath) {
        item.envienceFilePath = envienceFilePath.join('|');
      }
    });
    const hide = this.loadingMessage('正在更新数据,请稍后...');
    this.execHttp('totalnumberofclinics/updateRecords', {
      user: this.props.currentUser.id,
      records: JSON.stringify(obj),
    })
      .then(resp => {
        hide();
        const { success } = resp;
        if (success) {
          this.successMessage('数据提交成功');
          this.listAllByUser();
        } else {
          this.errorMessage('数据提交失败,请稍后尝试');
        }
      })
      .catch(reason => {
        hide();
      });
  };

  render() {
    const { currentUser, isLoading, form } = this.props;
    const { selectedYear, years, data } = this.state;

    const uploadButton = (
      <div>
        <Icon type={'plus'} />
        {/*<div className="ant-upload-text">Upload</div>*/}
      </div>
    );

    return (
      <PhotoProvider bannerVisible={false} maskOpacity={0.9}>
        <div className={styles.totalNumberofClinics}>
          <Card bordered={true} title={'诊疗总量列表'}></Card>
          <Card bordered={true} className={styles.contentBox}>
            {isLoading ? (
              <SpinBox>
                <Spin></Spin>
              </SpinBox>
            ) : (
              <>
                {/*基本信息*/}
                <Descriptions bordered title="基本信息" size={'middle'} column={3}>
                  <Descriptions.Item label={<div style={{ width: '100px' }}>机构名称</div>}>
                    <div style={{ width: '150px' }}>{currentUser.orgName}</div>
                  </Descriptions.Item>
                  <Descriptions.Item label={<div style={{ width: '100px' }}>筛查年度</div>}>
                    <div style={{ width: '250px' }}>
                      <Select
                        defaultValue={selectedYear}
                        style={{ width: '100%' }}
                        onChange={this.handleYearChange}
                      >
                        {years.map((item, index) => {
                          return (
                            <Option value={item} key={index}>
                              {item}
                            </Option>
                          );
                        })}
                      </Select>
                    </div>
                  </Descriptions.Item>
                </Descriptions>
                {/*胃镜总量信息*/}
                <Descriptions
                  bordered
                  title="胃镜总量信息"
                  size={'middle'}
                  column={3}
                  style={{ marginTop: '16px' }}
                >
                  {data.length > 0
                    ? data
                        .filter((item, index) => {
                          return index < this.state.nowMonth;
                        })
                        .map((item, index) => {
                          return (
                            <Fragment key={index}>
                              <Descriptions.Item
                                label={
                                  <div style={{ width: '100px' }}>
                                    {item.uploadMonthText}月份数量
                                  </div>
                                }
                              >
                                <div style={{ width: '150px' }}>
                                  {item.auditStatus === 1 || item.auditStatus == 0 ? (
                                    // 审核通过
                                    <InputNumber
                                      value={item.amounts}
                                      disabled={true}
                                      onChange={value => {
                                        this.handleNumberChange({ value, index });
                                      }}
                                      placeholder={'请输入数量'}
                                      style={{ width: '100%' }}
                                    ></InputNumber>
                                  ) : (
                                    <InputNumber
                                      value={item.amounts}
                                      onChange={value => {
                                        this.handleNumberChange({ value, index });
                                      }}
                                      placeholder={'请输入数量'}
                                      style={{ width: '100%' }}
                                    ></InputNumber>
                                  )}
                                </div>
                              </Descriptions.Item>
                              <Descriptions.Item
                                label={
                                  <div style={{ width: '100px' }}>
                                    {item.uploadMonthText}月份佐证
                                  </div>
                                }
                              >
                                <div
                                  style={{
                                    display: 'flex',
                                    flexDirection: 'column',
                                  }}
                                >
                                  {/*TODO:此处的envienceFileUrl为数组,此时需要对数组进行遍历*/}
                                  <div
                                    style={{
                                      display: 'flex',
                                      width: '100%',
                                      flexWrap: 'wrap',
                                    }}
                                  >
                                    {item.envienceFileUrl &&
                                    item.envienceFileUrl.length > 0 &&
                                    Array.isArray(item.envienceFileUrl)
                                      ? item.envienceFileUrl.map((url, imgIndex) => {
                                          return (
                                            <ThumbnailBox key={imgIndex}>
                                              <PhotoView src={`${njzdImgPrefixUrl}${url}`}>
                                                <div style={{ position: 'relative' }}>
                                                  <img
                                                    className={'thumbnailImage'}
                                                    src={`${njzdImgPrefixUrl}${url}`}
                                                  />
                                                </div>
                                              </PhotoView>
                                              {/*删除*/}
                                              <Popconfirm
                                                title="确定删除吗?"
                                                onConfirm={() => {
                                                  this.handleDelImage({ index, url });
                                                }}
                                              >
                                                <div
                                                  style={{
                                                    display:
                                                      item.auditStatus === 0 ||
                                                      item.auditStatus === 1
                                                        ? 'none'
                                                        : '',
                                                  }}
                                                  className={'delBtn'}
                                                  onClick={event => {
                                                    event.preventDefault();
                                                  }}
                                                >
                                                  <span>删除</span>
                                                </div>
                                              </Popconfirm>
                                            </ThumbnailBox>
                                          );
                                        })
                                      : null}
                                    {/*待审核,审核已通过状态下,不允许继续上传*/}
                                    {item.auditStatus === 0 || item.auditStatus === 1 ? null : (
                                      <Upload
                                        name="file"
                                        accept=".jpg,.jpeg,.png"
                                        listType="picture-card"
                                        className="avatar-uploader"
                                        disabled={this.state.isUploading}
                                        showUploadList={false}
                                        action={`/api/file/file/uploadFile4CerEndoscopicDiagnosis`}
                                        beforeUpload={this.handleUploadBefore}
                                        onChange={info => {
                                          this.handleUploadChange({ info, index });
                                        }}
                                        style={{ width: '60px', height: '60px' }}
                                      >
                                        {uploadButton}
                                      </Upload>
                                    )}
                                  </div>

                                  <UploadHintText>请上传当月工作站胃镜诊疗数量照片</UploadHintText>
                                </div>
                              </Descriptions.Item>
                              <Descriptions.Item label={<div style={{ width: '100px' }}>状态</div>}>
                                <div style={{ width: '200px' }}>
                                  {item.auditStatus == 2 ? (
                                    <Tag color="red">{item.auditStatusText}</Tag>
                                  ) : null}
                                  {item.auditStatus == 1 ? (
                                    <Tag color="green">{item.auditStatusText}</Tag>
                                  ) : null}
                                  {item.auditStatus == 0 ? <Tag>{item.auditStatusText}</Tag> : null}
                                </div>
                              </Descriptions.Item>
                            </Fragment>
                          );
                        })
                    : null}
                </Descriptions>

                <FooterBox>
                  <Popconfirm title="确定执行当前操作吗?" onConfirm={this.handleSubmitRecord}>
                    <Button type={'primary'}>提交</Button>
                  </Popconfirm>
                </FooterBox>
              </>
            )}
          </Card>
        </div>
      </PhotoProvider>
    );
  }

  handleNumberChange = ({ value, index }) => {
    const { data } = this.state;
    data[index].amounts = value;
    this.setState({
      data: [...data],
    });
  };

  /**
   * 筛查年度改变
   * @param value
   */
  handleYearChange = value => {
    this.setState({
      selectedYear: value,
    });
    this.listAllByUser();
  };

  handleUploadBefore = (file, fileList) => {
    this.setState({ isUploading: true }, () => {
      this.hide = this.loadingMessage('正在上传...');
    });
    return true;
  };

  /**
   * 删除图片
   * @param index 数据源下的索引
   * @param url 图片地址
   */
  handleDelImage = ({ index, url }) => {
    const { data } = this.state;
    // 通过索引定位到具体的数据
    const tmp = data[index];
    // 根据url找到具体的图片位置
    const tmpIndex = tmp.envienceFileUrl.findIndex(item => item == url);
    if (tmpIndex > -1) {
      tmp.envienceFileUrl.splice(tmpIndex, 1);
      tmp.envienceFilePath.splice(tmpIndex, 1);
    }
    // // 文件访问地址
    // data[index].envienceFileUrl = null;
    // // 文件存储地址
    // data[index].envienceFilePath = null;
    this.setState({
      data: [...data],
    });
  };

  handleUploadChange = ({ info, index }) => {
    if (info.file.status !== 'uploading') {
      this.setState(
        {
          fileList: info.fileList,
        },
        () => {}
      );
    }
    if (info.file.status === 'done') {
      const response = info.file.response;
      const {
        data: { filePath, originalFilename },
      } = response;
      const arr = filePath.split('/');
      // 文件前缀
      const prefix = arr[arr.length - 2];
      const url = `${prefix}/${originalFilename}`;
      const { data } = this.state;
      let { envienceFileUrl, envienceFilePath } = data[index];
      envienceFileUrl = !envienceFileUrl ? [] : envienceFileUrl;
      envienceFilePath = !envienceFilePath ? [] : envienceFilePath;
      envienceFileUrl.push(url);
      envienceFilePath.push(filePath);
      // 文件访问地址
      data[index]['envienceFileUrl'] = envienceFileUrl;
      // 文件存储地址
      data[index]['envienceFilePath'] = envienceFilePath;
      this.setState({
        data: [...data],
        isUploading: false,
      });
      if (this.hide) {
        this.hide();
      }
      this.successMessage('上传成功');
    } else if (info.file.status === 'error') {
      this.errorMessage('文件上传出错,请联系管理员');
    }
  };

  /**
   * 提交数据
   * @param index
   */
  handleSubmitRecord = () => {
    const { data } = this.state;
    this.updateRecords({ data });
  };
}

export default TotalNumberofClinics;
